//
//  SettingAlertView.swift
//  Game
//
//  Created by woniu on 2025/8/25.
//

import Foundation
import UIKit
import Photos

class SettingAlertView: UIView {
    
    public var onSubmitBlock: (()->())?
    
    private var editGame:GameModel!
    private var viewList:[InputBar] = []
    private var titleLab:UILabel!
    private var nameField:UITextField!
    private var typeButton:DownSelectBar!
    
    private var scrollView:UIScrollView!
    private var cancelButton:UIButton!
    private var submitButton:UIButton!
    private var addRowButton:UIButton!
    private var selectedUploadIndex = 0
    
    override init(frame: CGRect){
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        self.backgroundColor = .white
        titleLab = UILabel()
        titleLab.textAlignment = .center
        titleLab.text = "添加内容"
        self.addSubview(titleLab)
        
        scrollView = UIScrollView()
        self.addSubview(scrollView)
        
        nameField = UITextField()
        nameField.placeholder = "添加名字、描述"
        nameField.leftViewMode = .always
        nameField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: 40))
        nameField.clearButtonMode = .unlessEditing
        nameField.textColor = .black
        nameField.font = UIFont.systemFont(ofSize: 17)
        nameField.borderSet(Colors.title3, 0.5)
        nameField.circular5()
        self.addSubview(nameField)
        
        typeButton = DownSelectBar(frame: .zero)
        typeButton.update(title: nil)
        typeButton.itemPressedBlock = {[weak self]in
            self?.alertChoseType()
        }
        self.addSubview(typeButton)
        
        cancelButton = UIButton(type:.custom)
        cancelButton.backgroundColor = .white
        cancelButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        cancelButton.borderSet(Colors.title3, 1)
        cancelButton.setTitle("取消", for: .normal)
        cancelButton.setTitleColor(Colors.title3, for: .normal)
        cancelButton.circular5()
        cancelButton.addTarget(self, action: #selector(onDismiss(sender:)), for: .touchUpInside)
        self.addSubview(cancelButton)
        
        
        addRowButton = UIButton(type:.custom)
        addRowButton.backgroundColor = .white
        addRowButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        addRowButton.borderSet(Colors.title3, 1)
        addRowButton.setTitle("添加单词", for: .normal)
        addRowButton.setTitleColor(Colors.title3, for: .normal)
        addRowButton.circular5()
        addRowButton.addTarget(self, action: #selector(onAdd), for: .touchUpInside)
        self.addSubview(addRowButton)
        
        submitButton = UIButton(type: .custom)
        submitButton.backgroundColor = Colors.blue
        submitButton.setTitle("确定", for: .normal)
        submitButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        submitButton.circular5()
        submitButton.addTarget(self, action: #selector(onSubmit), for: .touchUpInside)
        self.addSubview(submitButton)
        
    }
    
    @objc func onAdd(){
        let index = viewList.count
        _ = addRowView(index: index)
        self.setNeedsLayout()
    }
    
    private func alertChoseType(){
        let alert = SingleTablePicker(frame: .zero)
        let dataArray:[GameType] = GameType.cardTypes()
        let titles:[String] = dataArray.map{$0.rawValue}
        alert.onSelectedRowBlock = {[weak self](index,val)in
            self?.editGame.type = dataArray[index].rawValue
            self?.typeButton.update(title: val)
        }
        alert.show(dataArray: titles, pickerW: 400)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        titleLab.frame = CGRect(x: 0, y: 15, width: self.width, height: 30)
        typeButton.frame = CGRect(x: self.width-135, y: titleLab.frame.maxY+10, width: 120, height: 40)
        nameField.frame = CGRect(x: 15, y: typeButton.y, width: self.width-30-15-typeButton.width, height: 40)
        scrollView.frame = CGRect(x: 0, y: nameField.frame.maxY, width: self.width, height: self.height-nameField.frame.maxY-30-40)
        var lastY:CGFloat = 0
        for (index,view) in viewList.enumerated(){
            view.indexLab.text = "\(index+1)"
            view.frame = CGRect(x: 15, y: lastY, width: self.width-30, height: 60)
            lastY = view.frame.maxY
        }
        scrollView.contentSize = CGSize(width: scrollView.width, height: lastY+170)
        
        cancelButton.frame = CGRect(x: 15, y: self.height-20-40, width: 80, height: 40)
        addRowButton.frame = CGRect(x: (self.width-cancelButton.width)*0.5, y: cancelButton.y, width: cancelButton.width, height:cancelButton.height)
        submitButton.frame = CGRect(x: self.width-15-80, y: cancelButton.y, width: cancelButton.width, height: cancelButton.height)
    }
    
    @objc func onDismiss(sender:UIButton) {
        hidden()
    }
    
    @objc func onSubmit(){
        if editGame.key.isEmpty{
            editGame.key = DateUtil.currentDateTime(format: "yyyyMMddHHmmss")
        }
        
        self.editGame.name = nameField.text ?? ""
        if editGame.name.isEmpty{
            ToastView.show("请添加描述")
            return
        }
        if editGame.type.isEmpty || GameType(rawValue: editGame.type) == nil{
            ToastView.show("请选择类型")
            return
        }
        
        var wordItems:[WordItem] = []
        for bar in viewList{
            if let wordItem = bar.getWordItem(){
                //新增文件名
                if wordItem.imgName.isEmpty{
                    wordItem.imgName = "img_\(self.editGame.key)_\(bar.tag)_\(DateUtil.currentDate(format: "mmss"))"
                }
                //写入文件
                if wordItem.didModifyImg,let imgData = wordItem.image?.pngData(){
                    GameManager.share.saveOrReplace(name: wordItem.imgName, image: imgData)
                }
                wordItems.append(wordItem)
            }
        }
        if wordItems.isEmpty{
            ToastView.show("请添加子项")
            return
        }
        if wordItems.count < 3{
            ToastView.show("至少添加3项")
            return
        }
        
        editGame.words = wordItems
        GameManager.share.insertOrUpdate(game: editGame)
        hidden()
        onSubmitBlock?()
    }
    
    private func addRowView(index:Int)->InputBar{
        let bar = InputBar(frame: .zero)
        bar.tag = index
        bar.onPickerImgBlock = {[weak self]index in
            guard let `self` = self else { return }
            self.selectedUploadIndex = index
            self.selectImageFromAlbum()
        }
        scrollView.addSubview(bar)
        viewList.append(bar)
        return bar
    }
    
    private func update(game:GameModel){
        self.editGame = game
        self.nameField.text = game.name
        typeButton.update(title: game.type)
        for view in viewList{view.removeFromSuperview()}
        viewList.removeAll()
        
        for (i,word) in game.words.enumerated(){
            let bar = addRowView(index: i)
            bar.update(wordItem: word)
        }
        self.setNeedsLayout()
    }
}

extension SettingAlertView {
    
    public func hidden() {
        self.superview?.removeFromSuperview()
    }
    
    public func show(vc:UIViewController,game:GameModel?) {
        if let game = game{
            self.update(game: game)
        }
        
        let bgView = UIButton(type: .custom)
        bgView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        bgView.frame = vc.view.bounds
        vc.view.addSubview(bgView)
        let viewSize = vc.view.size
        let alertW:CGFloat = Utils.isPad() ? 500 : 350
        let alertH:CGFloat = Utils.isPad() ? 750 : 600
        self.frame = CGRect(x: (viewSize.width-alertW)*0.5, y:(viewSize.height-alertH)*0.5, width:alertW, height: alertH)
        self.layer.cornerRadius = 5
        self.layer.masksToBounds = true
        bgView.addSubview(self)
    }
}

extension SettingAlertView{
    // 触发选择图片的方法（例如按钮点击）
    func selectImageFromAlbum() {
        // 检查相册访问权限
        checkPhotoLibraryPermission { [weak self] granted in
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                guard granted else {
                    self.showPermissionAlert()
                    return
                }
                self.superview?.isHidden = true
                
                let imagePicker = UIImagePickerController()
                imagePicker.sourceType = .photoLibrary
                imagePicker.allowsEditing = true
                imagePicker.delegate = self
                MyNavigator.getTopVC()?.present(imagePicker, animated: true, completion: nil)
            }
        }
    }
    
    // 检查相册权限
    private func checkPhotoLibraryPermission(completion: @escaping (Bool) -> Void) {
        switch PHPhotoLibrary.authorizationStatus(for: .readWrite) {
        case .authorized:
            completion(true)
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization(for: .readWrite) { status in
                completion(status == .authorized)
            }
        case .denied, .restricted:
            completion(false)
        case .limited:
            completion(true)
        @unknown default:
            completion(false)
        }
    }
    
    // 显示权限不足提示
    private func showPermissionAlert() {
        let alert = UIAlertController(
            title: "无法访问相册",
            message: "请在设置中允许应用访问您的相册",
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        alert.addAction(UIAlertAction(title: "设置", style: .default) { _ in
            guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { return }
            UIApplication.shared.open(settingsURL)
        })
        MyNavigator.getTopVC()?.present(alert, animated: true)
    }
    
}

extension SettingAlertView: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    // 图片选择完成回调
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let selectedImage = info[.editedImage] as? UIImage {
            viewList[self.selectedUploadIndex].didSelected(icon:selectedImage)
        }
        self.superview?.isHidden = false
        picker.dismiss(animated: true, completion: nil)
    }
}
